using Bean.Entity.Constant;
using Bean.Entity.Enum;
using Bean.Entity.Model;
using Bean.Infrastructure;
using Newtonsoft.Json;
using System;
using Bean.Entity.Dto.PolicyPushDto;

namespace Bean.ProductService;

/// <summary>
///生成政策基类
/// </summary>
public abstract class BaseProductService
{
    /// <summary>
    ///政策关键字
    /// </summary>
    public string PolicyKeyWordCode;

    /// <summary>
    /// 规则文本
    /// </summary>
    public string RuleText { get; set; }

    /// <summary>
    /// </summary>
    public PolicyOTAOperateTypeEnum OtaOperateType { get; set; }


    /// <summary>
    ///     操作编码
    /// </summary>
    public string SerialNo { get; set; }

    /// <summary>
    ///     采购商编码集合
    /// </summary>
    public List<string> SPCodes { get; set; }

    /// <summary>
    /// 政策运价基类
    /// </summary>
    public List<BasePolicyPoolInfo> policyBasicList { get; set; }

    /// <summary>
    ///展位字典
    /// </summary>
    // public Dictionary<CIDEnum, List<Exhibit>> exhibitDic { get; set; }

    /// <summary>
    /// </summary>
    public List<PolicyProductTaskDto.AirLinePolicy> AirLinePolicyList { get; set; }

    /// <summary>
    /// 对应要推送的平台和 政策类型
    /// </summary>
    public Dictionary<CIDEnum, List<PolicyTypeEnum>> OtaDic { get; set; }

    //【新增】初始化方法
    private void InitPolicyData()
    {
        if (string.IsNullOrWhiteSpace(PolicyKeyWordCode))
        {
            throw new NullReferenceException("政策关键字不能为空");
        }

        var policyProductKey = PolicyConstant.PolicyCodeQueue(PolicyKeyWordCode);
        var queue = new RedisQueue(policyProductKey);
        var message = queue.Dequeue();
        if (string.IsNullOrWhiteSpace(message)) throw new NullReferenceException($"获取{PolicyKeyWordCode}队列数据为空");

        var task = JsonConvert.DeserializeObject<PolicyProductTaskDto>(message);

        // faretypeDic = task?.faretypeDic ?? new Dictionary<CIDEnum, List<PolicyFareTypeEnum>>();
        SerialNo = task?.SerialNo ?? "";
        // exhibitDic = task?.exhibitDic ?? new Dictionary<CIDEnum, List<Exhibit>>();
        SPCodes = task?.SPCodes ?? [];
        OtaOperateType = task!.OperateType;
        SerialNo = task.SerialNo ?? "";
        RuleText = task.RuleText;
        AirLinePolicyList = task?.AirLinePolicyList ?? [];
    }

    ///  【新增】构造函数
    protected BaseProductService(string policyKeyWordCode)
    {
        PolicyKeyWordCode = policyKeyWordCode;
        InitPolicyData(); // 进行初始化
    }

    /// <summary>
    ///删除政策逻辑
    /// </summary>
    protected virtual Task DelPolicy()
    {
        throw new NotImplementedException();
    }

    /// <summary>
    ///生成政策逻辑
    /// </summary>
    protected abstract Task GeneratePolicy();


    /// <summary>
    /// 执行政策流程：
    /// 先删除再生成
    /// </summary>
    public Task ExecutePolicyAsync()
    {
        // 先删除政策
        DelPolicy();

        // 如果是更新操作，则额外生成政策
        if (OtaOperateType == PolicyOTAOperateTypeEnum.DeleteAndUpload) GeneratePolicy();

        if (policyBasicList.Count == 0)
        {
            throw new NullReferenceException("生成政策数据为空");
        }

        //循环台子
        foreach (var otaitem in OtaDic)
        {
            // 循环政策类型
            var policyTypeList = otaitem.Value;
            foreach (var polictTpyeItem in policyTypeList)
            {
                // 循环政策
                if (polictTpyeItem == PolicyTypeEnum.YLX_GB)
                {
                    // 易旅行公布政策
                    foreach (var item in policyBasicList)
                    {
                        var etravePublic = new OtaEtravelPublicPolicyPushDto.Builder()
                            .SetExternalPolicyId(Guid.NewGuid().ToString())
                            .SetPolicyCode(item.policyCode)
                            .SetTravelType(item.tripType)
                            .SetAirline(item.airLine)
                            .SetDepCities(item.depAirport)
                            .SetArrCities(item.arrAirport)
                            .SetRouteForbid(item.forbidAirlines)
                            .SetCabin(item.cabin)
                            .SetCanSharingAirline(item.IsCanSharingAirline)
                            .SetSharingAirline(item.interlineAirlineCode)
                            .SetSharingAirlineForbid(item.sharingAirlineForbid)
                            .SetGoFlightRestrictType(item.goFlightRestrictType)
                            .SetGoFlightRestrict(item.flightNumbers)
                            .SetGoDateRestrict(item.tripStartDate, item.tripEndDate)
                            .SetGoDateRestrictForbid(item.tripExceptStartDate, item.tripExceptEndDate)
                            .SetSaleDateRestrict(item.saleStartDate, item.saleEndDate)
                            .SetGoTimeRestrict(item.tripStartTime, item.TripEndTime)
                            .SetWeekRestrict(item.dayCondition)
                            .SetAdvanceSaleDay(item.beforeNdays?.ToString() ?? "")
                            .SetMaxSaleDay(item.afterNdays?.ToString() ?? "")
                            .SetWorkTime()
                            .SetPassengerType(item.passengerType)
                            .SetSaleRetention(item.returnPoint)
                            .SetSaleRebase(item.returnPrice)
                            .SetMinPrice(item.minPrice.ToString())
                            .SetMaxPrice(item.maxPrice.ToString())
                            .SetIsNeedPrice(item.needPata.ToString()) //是否PAT验价  (1 是,0 否)
                            .SetTestPriceOffice(item.patofficecode)
                            .SetUpPrice("0")
                            .SetAgeRestrict("")
                            .SetCredentialType("0")
                            .SetIdcardPrefix("")
                            .SetReimbursementVoucher("0")
                            .SetIsNeedBook("1")
                            .SetIsReserveSeat(item.isneedpnr.ToString())
                            .SetSeatCount(item.seatLimit?.ToString() ?? "")
                            .SetTicketType(item.ticketType)
                            .SetBookingOffice(item.officecode)
                            .SetTicketOffice("")
                            .SetAuthorizeOfficeCode("")
                            .SetAutoTicketing("0")
                            .SetMemo(item.policyRemark).Build();
                    }
                }
                else if (polictTpyeItem == PolicyTypeEnum.YLX_SY)
                {
                    foreach (var item in policyBasicList)
                    {
                        // 易旅行私有政策
                        var etravePrivate = new OtaEtravelPrivatePolicyPushDto.Builder()
                            .SetExternalPolicyId(Guid.NewGuid().ToString())
                            .SetPolicyCode(item.policyCode)
                            .SetProductType(item.ProductType)
                            .SetTravelType(item.tripType)
                            .SetAirline(item.airLine)
                            .SetDepCities(item.depAirport)
                            .SetArrCities(item.arrAirport)
                            .SetRouteForbid(item.forbidAirlines)
                            .SetCabin(item.cabin)
                            .SetGoFlightRestrictType(item.goFlightRestrictType)
                            .SetGoFlightRestrict(item.flightNumbers)
                            .SetGoDateRestrict(item.tripStartDate, item.tripEndDate)
                            .SetgoDateRestrictForbid(item.tripExceptStartDate, item.tripExceptEndDate)
                            .SetSaleDateRestrict(item.saleStartDate, item.saleEndDate)
                            .SetGoTimeRestrict(item.tripStartTime, item.TripEndTime)
                            .SetWeekRestrict(item.dayCondition)
                            .SetAdvanceSaleDay(item.beforeNdays?.ToString() ?? "")
                            .SetMaxSaleDay(item.afterNdays?.ToString() ?? "")
                            .SetPassengerType(item.passengerType)
                            .SetCanShare(item.shareShowAct.ToString())
                            .SetCanOperateAirline(item.CanOperateAirline)
                            .SetIncludeShareAirlines(item.interlineAirlineCode)
                            .SetExcludeShareAirlines(item.sharingAirlineForbid)
                            .SetTicketSource(item.ticketSource)
                            .SetTicketPrice(item.farePrice.ToString())
                            .SetAirlineRetention("0")
                            .SetDirectDecrease("0")
                            .SetNfdCharge(item.nfdCharge)
                            .SetIsNeedPrice(item.needPata.ToString())
                            .SetTestPriceOffice(item.patofficecode)
                            .SetUpPrice("0")
                            .SetSaleRetention(item.ReturnPointPercentage.ToString())
                            .SetSaleRebase(item.returnPrice.ToString())
                            .SetMinPrice(item.minPrice.ToString())
                            .SetMaxPrice(item.maxPrice.ToString())
                            .SetIsNeedBook("1")
                            .SetIsReserveSeat(item.isneedpnr.ToString())
                            .SetSeatCount(item.seatLimit?.ToString() ?? "")
                            .SetTicketType(item.ticketType)
                            .SetBookingOffice(item.officecode)
                            .SetTicketOffice("")
                            .SetAuthorizeOfficeCode("")
                            .SetAutoTicketing("0")
                           .SetMemo(item.policyRemark).Build();
                            
                    }
                }
            }
        }


        return Task.CompletedTask;
    }
}